package com.mages.classification.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

@Component
public class AvailabilityService {
    private static String availabilityTxt;

    @Value("${SERVICE_AVAILABILITY:share/availability.txt}")
    public void setAvailability(String availabilityTxt) {
        AvailabilityService.availabilityTxt = availabilityTxt;
    }

    int turn = 0;

    @Scheduled(cron="0/60 * *  * * ? ")   //每1分钟执行一次
    public void execute(){
        String encoding="GBK";
        //availabilityTxt
        File file = new File(availabilityTxt);
        if (!file.exists()) {
            boolean flag = false;
            try {
                flag = file.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (!flag) {
                System.out.println("failed to make dir: availabilityTxt");
            }
        }

        //将记录写入txt文件
        Date date = new Date();
        SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
        // 设置时区为中国时区
        TimeZone chinaTimeZone = TimeZone.getTimeZone("Asia/Shanghai");
        timeFormat.setTimeZone(chinaTimeZone);

        String currentTime = timeFormat.format(date);
        String content = currentTime+","+turn;
        turn++;
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(availabilityTxt, true)));
            out.write(content+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
